﻿using ARchGL.Declaration.Platform.Domain.Entities;
using ARchGL.Declaration.Platform.Domain.Events;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Net;
using TDF.Core.Configuration;
using TDF.Core.Event;
using TDF.Core.Ioc;
using TDF.Core.Log;

namespace ARchGL.Declaration.Platform.Service.EventHandles
{
    /// <summary>
    /// 分项状态更新
    /// 当工程验收状态发生变化时通过此接口将变化后的状态推送给智慧工地系统。
    /// </summary>
    public class ProjectStatusChangeHandle : IConsumer<ProjectStatusChangeEvent>
    {
        /// <summary>
        /// 分项状态更新
        /// </summary>
        /// <param name="eventEntity"></param>
        public void Handler(ProjectStatusChangeEvent eventEntity)
        {
            var configs = new Configs();
            var site = configs.GetValue("SiteUrl");
            if (!site.Contains("au.typeo.org")) return;

            var url = "api/open/v2/quality/acceptance/changePartStatus";
            var json = string.Empty;
            var status = PushStatus.成功;
            var message = string.Empty;
            try
            {
                if (eventEntity == null) LogFactory.GetLogger().Info($"工程文件推送失败-没有获取到数据");

                var postdata = new
                {
                    eventEntity.projectCode,
                    eventEntity.partCode,
                    eventEntity.status
                };
                var request = new RestRequest(url, Method.POST);
                json = request.JsonSerializer.Serialize(postdata);
                var responsePost = BaseMethod.ExecuteRequest(request, json);
                message = responsePost.Content;
                if (responsePost.StatusCode != HttpStatusCode.OK)
                {
                    status = PushStatus.失败;
                    LogFactory.GetLogger().Info($"工程状态变更推送【失败】：{eventEntity.projectCode}-{eventEntity.partCode} | {message}");
                }
                else
                {
                    LogFactory.GetLogger().Info($"工程状态变更推送成功：{eventEntity.projectCode}-{eventEntity.partCode} | {message}");
                }
            }
            catch (Exception ex)
            {
                status = PushStatus.失败;
                message = ex.Message;
                LogFactory.GetLogger().Error($"工程状态变更推送【异常】：", ex);
            }

            //记录发送数据
            Ioc.Resolve<IPushService>().Save(new Push_Project_History
            {
                Url = url,
                Data = json,
                Message = message,
                Status = status,
                Type = PushType.状态更新,
            });
        }
    }
}
